/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.mapper;

import org.retabel.persistence.dao.document.ExportConfigurationDao;
import org.retabel.persistence.dao.report.ReportDesignPackageDao;
import org.retabel.persistence.entity.document.DocumentConfiguration;
import org.retabel.persistence.entity.document.SectionConfiguration;
import org.retabel.persistence.entity.document.SectionConfigurationTypeEnum;
import xsd.documentconfiguration.DynamicDocument;
import xsd.documentconfiguration.ObjectFactory;
import xsd.documentconfiguration.StaticSection;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Class description.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 15:44 12.08.11
 *
 * @author Burt Parkers
 * @version 1.0
 */
@Stateless
public class XmlDocumentConfigurationMapperBean extends XmlDocumentConfigurationMapperBaseBean implements XmlDocumentConfigurationMapper {

    /** Dao to access the designs. */
    @EJB
    private ReportDesignPackageDao reportDesignDao;

    /** Dao to access the export configurations. */
    @EJB
    private ExportConfigurationDao exportConfigurationDao;

    /** Xml section configuration mapper. */
    @EJB
    private XmlSectionConfigurationMapper xmlSectionConfigurationMapper;

    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public DocumentConfiguration unmarshal(byte[] documentConfigurationData) throws XmlConfigurationMappingException {
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(documentConfigurationData);

            xsd.documentconfiguration.DocumentConfiguration documentConfiguration = unmarshal(inputStream);

            DocumentConfiguration docConfiguration;
            if (documentConfiguration.getStaticDocument() != null) {
                docConfiguration = mapStaticDocumentConfiguration(documentConfiguration.getStaticDocument());
            } else {
                docConfiguration = mapDynamicDocumentConfiguration(documentConfiguration.getDynamicDocument());
            }
            return docConfiguration;
        } catch (JAXBException e) {
            throw new XmlConfigurationMappingException("Error while parsing XmlConfiguration: " + e.getMessage(), e);
        }
    }

    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    public JAXBElement<xsd.documentconfiguration.DocumentConfiguration> marshal(DocumentConfiguration documentConfiguration) {
        ObjectFactory documentConfigurationObjectFactory = new ObjectFactory();

        xsd.documentconfiguration.DocumentConfiguration xmlDocumentConfiguration =
            documentConfigurationObjectFactory.createDocumentConfiguration();

        DynamicDocument dynamicDocument = documentConfigurationObjectFactory.createDynamicDocument();
        dynamicDocument.setName(documentConfiguration.getName());
        dynamicDocument.setVersion(documentConfiguration.getVersion());

        xsd.documentconfiguration.DynamicDocument.SectionConfigurations sectionConfigurations =
            documentConfigurationObjectFactory.createDynamicDocumentSectionConfigurations();

        for (SectionConfiguration sectionConfiguration : documentConfiguration.getSectionConfigurations()) {
            if (SectionConfigurationTypeEnum.TEMPORARY.equals(sectionConfiguration.getConfigurationType())) {
                xsd.sectionconfiguration.SectionConfiguration xmlSectionConfiguration =
                    (xmlSectionConfigurationMapper.marshal(sectionConfiguration)).getValue();

                sectionConfigurations.getStaticSectionOrDynamicSection().add(xmlSectionConfiguration);
            } else if (SectionConfigurationTypeEnum.PERMANENT.equals(sectionConfiguration.getConfigurationType())) {
                StaticSection xmlStaticSection = documentConfigurationObjectFactory.createStaticSection();
                xmlStaticSection.setRef(sectionConfiguration.getName());
                xmlStaticSection.setVersion(sectionConfiguration.getVersion());

                sectionConfigurations.getStaticSectionOrDynamicSection().add(xmlStaticSection);
            } else {
                throw new IllegalStateException(
                    "not supported section configuration type implementation: " + sectionConfiguration.getConfigurationType());
            }
        }

        xmlDocumentConfiguration.setDynamicDocument(dynamicDocument);

        dynamicDocument.setSectionConfigurations(sectionConfigurations);

        return documentConfigurationObjectFactory.createDocumentConfiguration(xmlDocumentConfiguration);
    }

    /**
     * Maps a dynamic document configuration part, defined in the xml configuration.
     *
     * @param dynamicDocument the dynamic docment configuration.
     * @return the created data set.
     * @throws XmlConfigurationMappingException if a persistent data set cannot be found.
     */
    private DocumentConfiguration mapDynamicDocumentConfiguration(DynamicDocument dynamicDocument)
        throws XmlConfigurationMappingException {
        DocumentConfiguration documentConfiguration = new DocumentConfiguration();
        documentConfiguration.setName(dynamicDocument.getName());
        documentConfiguration.setVersion(dynamicDocument.getVersion());

        Collection<SectionConfiguration> sectionConfigurationCollection = new LinkedList<>();

        DynamicDocument.SectionConfigurations sectionConfigurations = dynamicDocument.getSectionConfigurations();

        List<Object> staticSectionOrDynamicSections = sectionConfigurations.getStaticSectionOrDynamicSection();

        for (Object staticSectionOrDynamicSection : staticSectionOrDynamicSections) {
            if (staticSectionOrDynamicSection instanceof StaticSection) {
                StaticSection staticSection = (StaticSection) staticSectionOrDynamicSection;

                sectionConfigurationCollection.add(mapStaticSection(staticSection));
            } else {
                xsd.sectionconfiguration.SectionConfiguration dynamicSection =
                    (xsd.sectionconfiguration.SectionConfiguration) staticSectionOrDynamicSection;

                sectionConfigurationCollection.add(xmlSectionConfigurationMapper.mapSectionConfiguration(dynamicSection));
            }
        }

        documentConfiguration.setSectionConfigurations(sectionConfigurationCollection);

        return documentConfiguration;
    }

    private xsd.documentconfiguration.DocumentConfiguration unmarshal(InputStream inputStream) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(xsd.documentconfiguration.ObjectFactory.class);
        Unmarshaller u = jc.createUnmarshaller();

        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = schemaFactory.newSchema(getClass().getClassLoader().getResource("documentConfiguration.xsd"));
            u.setSchema(schema);
        } catch (Exception e) {
            throw new JAXBException(e);
        }
        return ((JAXBElement<xsd.documentconfiguration.DocumentConfiguration>) u.unmarshal(inputStream)).getValue();
    }

}
